package doc;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Sketch {

	public static int INK = 0x0001;
	public static int CONTEXT = 0x0010;

	private static int count = 0;

	public static int generateId() {
//		System.out.println(count);
		return count++;
	}

	public static void mergeId(int newId) {
//		System.out.println("count before: " + count);
		count = Math.max(newId + 1, count);
//		System.out.println("count after: " + count);
	}

//	private List<Stroke> ink;

	private List<Stroke> strokes;

	public Sketch() {
		strokes = new ArrayList<Stroke>();

	}

	public boolean appendStroke(Stroke s) {
		mergeId(s.getId());
		return strokes.add(s);
	}

	public List<Stroke> getStrokes() {
		return strokes;
	}

	public boolean removeStroke(Stroke s) {
		return strokes.remove(s);
	}

	public boolean removeStrokes(Collection sts) {
		return strokes.removeAll(sts);
	}

	public void removeStrokesAll() {
		removeStrokes(getStrokes());
	}

	public Stroke getStrokeById(int id) {
		for (Iterator<Stroke> it = strokes.iterator(); it.hasNext(); ) {
			Stroke s = it.next();
			if (s.getId() == id)
				return s;
		}
		return null;
	}

	public void removeAll() {
//		removeShapesAll();
		removeStrokesAll();
//		removeInkAll();
	}

	public boolean appendStrokes(Collection list) {
		boolean suc = true;
		for (Object o : list) {
			if (o instanceof Stroke) {
				if (appendStroke((Stroke)o))
					suc = false;
			}
		}
		return suc;
	}

	public void print() {
		System.out.println("Sketch content:");
		System.out.println("\tink - " + strokes.size());
//		System.out.println("\tshapes - " + shapes.size());
	}

	public void saveToFile(File file, int option) {
		if ((option & INK) == INK) {
			try {
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));

				for (Stroke stroke : getStrokes()) {
					bw.write(stroke.toSimpleML() + "\n");
				}

				bw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void readFromFile(File file) {
		removeAll();

		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

			String one = null;
			while ((one = br.readLine()) != null) {
				appendInk(Stroke.parseSimpleML(one));
			}

			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void appendInk(Stroke s) {
		appendStroke(s);

//		ink.add(s);
	}

//	public List<Stroke> getInk() {
//		return ink;
//	}
}
